import { DateRangeSelector } from '@/components/date-range-selector';
import { DetailResult } from '@/pages/types/type';
import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
import { AutoCenter, Modal, Toast } from 'antd-mobile';
import { ToastHandler } from 'antd-mobile/es/components/toast';
import * as echarts from 'echarts';
import { useEffect, useRef, useState } from 'react';
import styles from '../index.less';
import { Action } from 'antd-mobile/es/components/action-sheet';
const dayjs = require('dayjs');
require('dayjs/plugin/quarterOfYear');
dayjs.extend(require('dayjs/plugin/quarterOfYear'));

/**
 * 产值统计
 */
interface PerformnaceStatistics {
  department: {
    label: string;
    value: number;
    name: string;
    sid: string;
    shortName?: string;
  };
  money: number;
}

export default ({ period }: { period: string }) => {
  const pfmnRef = useRef(null);
  const [performances, setPerformances] = useState<PerformnaceStatistics[]>([]);
  const [range, setRange] = useState<string[]>([]);
  async function getPerformances() {
    // 2024-07-28 星期六，加载产值统计信息
    fetch(
      `${urlPrefix}/api/performance-stats/by-oa-department-and-year-month/${range[0]}/${range[1]}`,
      getRequestInit(),
    )
      .then((rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(({ data, code }: DetailResult<PerformnaceStatistics[]>) => {
              if (code === 0) {
                setPerformances(data!);
              }
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
      });
  }

  useEffect(() => {
    if (range.length === 2) {
      getPerformances();
    }
  }, [range]);

  // echarts,绘制图表，产值
  useEffect(() => {
    if (!pfmnRef.current) {
      return;
    }

    const chart = echarts.init(pfmnRef.current);
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: 15,
        right: 15,
        bottom: 0,
        top: 50,
        containLabel: true,
      },
      legend: {
        data: ['产值'],
      },
      xAxis: [
        {
          type: 'category',
          data: performances.map(
            (p) => p.department.shortName || p.department.name,
          ),
          axisPointer: {
            type: 'shadow',
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
        },
      ],

      series: [
        {
          name: '产值',
          type: 'bar',
          data: performances.map((p) => (p.money / 10000).toFixed(4)),
          barWidth: '30%',
        },
      ],
    };

    chart.setOption(option);

    // 注意：这里需要返回一个清理函数，以确保在组件卸载时销毁ECharts实例
    return () => {
      chart.dispose();
    };
  }, [pfmnRef.current, performances]);

  const handler = useRef<ToastHandler>();
  async function expertExcel() {
    handler.current = Toast.show({
      icon: 'loading',
      content: '正在下载',
      maskClickable: false,
      duration: 0,
    });

    fetch(
      `${urlPrefix}/api/performance-stats/exportby-oa-department-and-year-month/${range[0]}/${range[1]}`,
      getRequestInit(),
    )
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          await rsp
            .json()
            .then(async ({ data, code, msg }: DetailResult<string>) => {
              if (code === 0) {
                handler.current?.close();
                Modal.show({
                  title: '已导出',
                  closeOnAction: true,
                  actions: [
                    {
                      key: 'download',
                      text: (
                        <AutoCenter>
                          <a href={data!} target="_blank" rel="noreferrer">
                            下载
                          </a>
                        </AutoCenter>
                      ),
                    },
                  ],
                  onAction: (action: Action, index: number) => {
                    console.log(action, ',index=', index);
                  },
                });
              } else {
                Toast.show({
                  icon: 'fail',
                  content: msg,
                  duration: 4000,
                });
              }
            })
            .catch((reason) => {
              Toast.show({
                icon: 'fail',
                content: `执行失败：${reason}`,
              });
            });
        }
      })
      .catch((reason: any) => {
        Toast.show({
          icon: 'fail',
          content: `执行失败：${reason}`,
        });
      })
      .finally(() => {
        //handler.current?.close();
      });
  }

  return (
    <>
      <div style={{ marginTop: '12px' }} className={styles.chartGroup}>
        <div className={styles.select}>
          <div onClick={expertExcel}>
            <i className="iconfont icon-xiazai" style={{ marginRight: 14 }}></i>
          </div>
          <DateRangeSelector
            period={period}
            onTimeChange={(a, b, type) => setRange([a, b])}
          />
        </div>

        <div className={styles.chart} ref={pfmnRef}></div>
      </div>
    </>
  );
};
